package v1

import (
	"github.com/gin-gonic/gin"
	"manager/bll"
	"manager/model"
	"manager/server/web/middleware"
	"manager/utils"
)

var Control = &control{}

func init() {
	// 注册路由
	RegisterRouter(Control)
}

type control struct{}

// Init 初始化路由
func (a *control) Init(r *gin.RouterGroup) {
	// web 路由
	g := r.Group("/control", middleware.Auth())
	{
		g.POST("/create", a.create)
		g.POST("/update", a.update)
		g.POST("/list", a.list)
		g.POST("/delete", a.delete)
		g.POST("/detail", a.find)
	}
	// app 路由
	appG := r.Group("app/control", middleware.Auth())
	{
		appG.POST("/create", a.create)
		appG.POST("/update", a.update)
		appG.POST("/list", a.list)
		appG.POST("/delete", a.delete)
		appG.POST("/detail", a.find)
	}
}

// create 创建
func (a *control) create(c *gin.Context) {
	var (
		in  = &model.ControlCreateRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if _, err = bll.Control.Create(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}

// update 更新
func (a *control) update(c *gin.Context) {
	var (
		in  = &model.ControlUpdateRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.Control.Update(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}

// list 列表查询
func (a *control) list(c *gin.Context) {
	var (
		in  = &model.ControlListRequest{}
		out = &model.ControlListResponse{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if out, err = bll.Control.List(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, out)
}

// list 列表查询
func (a *control) find(c *gin.Context) {
	var (
		in  = &model.ControlInfoRequest{}
		out = &model.ControlInfo{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if out, err = bll.Control.Find(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, out)
}

// delete 删除
func (a *control) delete(c *gin.Context) {
	var (
		in  = &model.ControlDeleteRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.Control.Delete(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}
